//
//  JuBaseEncode.swift
//  JuModule
//
//  Created by Juvid on 2018/4/28.
//  Copyright © 2018年 Juvid. All rights reserved.
//

import UIKit

open class JuBaseEncode: NSObject,NSCoding {
    public func copy(with zone: NSZone? = nil) -> Any {
        var cls: AnyClass = self.classForCoder
        let classType = cls as? NSObject.Type
        if let anObject = classType {
          let copy = anObject.init()
            while cls != JuBaseModel.classForCoder() {
                var count:UInt32 = 0
                let  properties = class_copyPropertyList(object_getClass(self),&count)
                for  i in 0..<numericCast(count) {
                    let char_f = property_getName((properties?[i])!);
                    let propertyName = String.init(utf8String: char_f)
                    let value = self.value(forKey: propertyName!)
                    if value != nil {
                        copy.setValue(value, forKey: propertyName!)
                    }
                    free(properties)
                    cls = cls.superclass()!
                }
            }
            return copy;
        }
        return self
//        let classType = self.classForCoder as? JuBaseEncode.Type
//        let copyCls = classType?.init(coder: <#T##NSCoder#>)
//        let classType = type(of: JuBaseEncode)
//        let copyCls = classType?.init(coder: nil)
//        return copyCls

    }
    //父类的init方法是必须去实现的
    override init() {
        super.init()
    }

    public func encode(with aCoder: NSCoder) {
        var cls:AnyClass = self.classForCoder
        while cls != JuBaseModel.classForCoder() {
            var count:UInt32 = 0
            let  properties = class_copyPropertyList(object_getClass(self),&count)
            for  i in 0..<numericCast(count) {
                let char_f = property_getName((properties?[i])!);
                let propertyName = String.init(utf8String: char_f)
                let value = self.value(forKey: propertyName!)
                if value != nil {
                    aCoder.encode(value, forKey: propertyName!)
                }
                free(properties)
                cls = cls.superclass()!
            }
        }
    }

    required public  convenience init?(coder aDecoder: NSCoder) {
        self.init()
        var cls:AnyClass = self.classForCoder
        while cls != JuBaseModel.classForCoder() {
            var count:UInt32 = 0
            let  properties = class_copyPropertyList(object_getClass(self),&count)
            for  i in 0..<numericCast(count) {
                let char_f = property_getName((properties?[i])!);
                let propertyName = String.init(utf8String: char_f)
                let value = aDecoder.decodeObject(forKey: propertyName!)
                if value != nil {
                    self.setValue(value, forKey: propertyName!)
                }
                free(properties)
                cls = cls.superclass()!
            }
        }
    }


}
